package com.example.demo.controller;

import com.example.demo.dto.CartItemDetailsDTO;
import com.example.demo.entity.ShoppingCart;
import com.example.demo.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    // 获取用户购物车
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<ShoppingCart>> getUserCart(@PathVariable Integer userId) {
        List<ShoppingCart> cartItems = shoppingCartService.getUserCart(userId);
        return ResponseEntity.ok(cartItems);
    }

    // 更新购物车商品数量
    @PutMapping("/update")
    public ResponseEntity<String> updateCartItem(@RequestBody ShoppingCart cartItem) {
        try {
            String result = shoppingCartService.updateCartItem(cartItem);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("更新购物车失败: " + e.getMessage());
        }
    }

    // 从购物车移除商品
    @DeleteMapping("/remove/{cartId}")
    public ResponseEntity<String> removeFromCart(@PathVariable Integer cartId) {
        try {
            String result = shoppingCartService.removeFromCart(cartId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("移除商品失败: " + e.getMessage());
        }
    }

    // 清空用户购物车
    @DeleteMapping("/clear/{userId}")
    public ResponseEntity<String> clearCart(@PathVariable Integer userId) {
        try {
            String result = shoppingCartService.clearCart(userId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("清空购物车失败: " + e.getMessage());
        }
    }

    @GetMapping("/total-items/{userId}")
    public ResponseEntity<Integer> getTotalCartItems(@PathVariable Integer userId) {
        Integer totalItems = shoppingCartService.getTotalCartItems(userId);
        return ResponseEntity.ok(totalItems);
    }

    @GetMapping("/details/{userId}")
    public ResponseEntity<List<CartItemDetailsDTO>> getCartDetails(@PathVariable Integer userId) {
        List<CartItemDetailsDTO> cartDetails = shoppingCartService.getCartDetails(userId);
        return ResponseEntity.ok(cartDetails);
    }

}
